import Vue from 'vue'
import VueRouter from 'vue-router'
import { Toast } from 'vant';
Vue.use(VueRouter)

// 解决路由跳转报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/index',
    name: 'index',
    meta:{title:'index'},
    component: () => import('../views/Index.vue'),
    children:[
      {
        path:"/home",
        name:"home",
        meta:{title:'首页'},
        component:() => import('../views/index/Home.vue')
      },
      {
        path:"/tuan",
        name:"tuan",
        meta:{title:'爆爆团'},
        component:() => import('../views/index/Tuan.vue')
      },
      {
        path:"/order",
        name:"order",
        meta:{title:'订单'},
        component:() => import('../views/index/Order.vue')
      },
      {
        path:"/mine",
        name:"mine",
        meta:{title:'我的'},
        component:() => import('../views/index/Mine.vue')
      },
      // {
      //   path:"/",
      //   redirect:"/home"
      // }
    ]
  },
  {
    path: '/login',
    name: 'login',
    meta:{title:'登录'},
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/register',
    name: 'register',
    meta:{title:'注册'},
    component: () => import('../views/Register.vue'),
  },
  {
    path: '/detail',
    name: 'detail',
    meta:{title:'详情页'},
    component: () => import('../views/Detail.vue'),
  },
  {
    path: '/collection',
    name: 'collection',
    meta:{title:'详情页'},
    component: () => import('../views/Collection.vue'),
  },
  // 重定向
  {
    path:"/",
    redirect:"/home"
  },
  // 404页面
  {
    path:"*",
    name:"no",
    meta:{title:'404'},
    component: () => import("@/views/NotFound.vue")
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const token = localStorage.getItem("token")
// 全局前置路由导航守卫
router.beforeEach((to,feom,next)=>{

  //动态更新网页标题
  document.title = to.meta.title;

  //获取localStorage中的登陆凭证
  const token = localStorage.getItem('token');
  if(to.path == "/register" ){
    next()
  }else if( to.path == "/order" || to.path == '/mine'){
    if(  token ){
      next()
    }else{
      Toast('登录后才能访问')
      next("/login")
    }
  }else{
    next()
  }
})

export default router
